package.cpath = "luaclib/?.so;3rd/lua-cjson/?.so;lualib/?.so;" 
local mysql = require "mysql"
local json   = require "cjson" 

require "config_redis"

MYSQL = {}  
 

local mysql_db
function MYSQL.get_mysql(  ) 
    if mysql_db == nil then 
        local function on_connect(db)
            db:query("set charset ".. mysql_args.charset);
        end 
        mysql_db = mysql.connect{
            host    = mysql_args.host,
            port    = mysql_args.port,
            database= mysql_args.database,
            user    = mysql_args.user,
            password= mysql_args.password,
            max_packet_size = 1024 * 1024,
            on_connect = on_connect,
        }
    end 
end
 

function MYSQL.get_one(sql)
    MYSQL.get_mysql()
    local ok = false 
    sql = sql .. ' limit 0,1'
    local res = mysql_db:query(sql) 
    if #res == 0 then
        return ok
    end
    ok = true 
    return res[1]
end

function MYSQL.get_all(sql)
    MYSQL.get_mysql()
    local ok = false 
    local res = mysql_db:query(sql) 
    if #res == 0 then
        return ok
    end  
    return res
end

function MYSQL.insert(sql)
    MYSQL.get_mysql() 
    local res = mysql_db:query(sql) 
    local ok = false
    if res and res.errno then
        return ok
    end
    ok = res.insert_id
    return ok
end

function MYSQL.update(sql)
    MYSQL.get_mysql() 
    mysql_db:query(sql) 
end


function MYSQL.del(sql)
    MYSQL.get_mysql() 
    mysql_db:query(sql) 
end


function MYSQL.addLog(uid,type,data)
    MYSQL.get_mysql() 
    local sql = "insert into `log` values   (0,"..uid..",'"..data.."',"..type..")"
    local res = mysql_db:query(sql)  
end


return MYSQL
